package com.alex.wechat.component.message.controller;

import java.io.IOException;
import java.net.URI;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import com.alex.wechat.app.config.WxAppContext;
import com.alex.wechat.component.message.entity.WxAppMsgTemplateEntity;
import com.alex.wechat.component.message.service.WxAppMsgTemplateServiceI;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.component.api.WxCompService;
import me.chanjar.weixin.component.api.app.impl.WxCompMaMessageTemplateServiceImpl.AddTemplateRequest;
import me.chanjar.weixin.component.api.app.impl.WxCompMaMessageTemplateServiceImpl.QueryTemplateTitleResponse;
import me.chanjar.weixin.component.bean.template.Paging;
import me.chanjar.weixin.component.bean.template.WxAppMsgTemplate;
import me.chanjar.weixin.component.bean.template.WxAppMsgTemplateLibKeyword;

/**
 * @Title: Controller
 * @Description: 微信消息模板
 * @author onlineGenerator
 * @date 2017-10-16 17:18:17
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/wxAppMsgTemplateController")
public class WxAppMsgTemplateController extends BaseController {
  /**
   * Logger for this class
   */
  private static final Logger logger = Logger.getLogger(WxAppMsgTemplateController.class);

  @Autowired
  private WxAppMsgTemplateServiceI wxAppMsgTemplateService;
  @Autowired
  private SystemService systemService;
  @Autowired
  private Validator validator;

  @Autowired
  private WxCompService wxComponentService;

  /**
   * 微信消息模板列表 页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "list")
  public ModelAndView list(HttpServletRequest request) {
    return new ModelAndView("com/gomore/wechat/component/message/wxAppMsgTemplateList");
  }

  /**
   * easyui AJAX请求数据
   * 
   * @param request
   * @param response
   * @param dataGrid
   * @param user
   */

  @RequestMapping(params = "datagrid")
  public void datagrid(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    CriteriaQuery cq = new CriteriaQuery(WxAppMsgTemplateEntity.class, dataGrid);
    // 查询条件组装器
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, wxAppMsgTemplate,
        request.getParameterMap());
    try {
      // 自定义追加查询条件
    } catch (Exception e) {
      throw new BusinessException(e.getMessage());
    }
    cq.add();
    this.wxAppMsgTemplateService.getDataGridReturn(cq, true);
    TagUtil.datagrid(response, dataGrid);
  }

  /**
   * 删除微信消息模板
   * 
   * @return
   */
  @RequestMapping(params = "doDel")
  @ResponseBody
  public AjaxJson doDel(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    wxAppMsgTemplate = systemService.getEntity(WxAppMsgTemplateEntity.class,
        wxAppMsgTemplate.getId());
    message = "微信消息模板删除成功";
    try {
      WxAppContext.setAppId(wxAppMsgTemplate.getAppId());
      // 删除微信模板消息
      wxComponentService.getMaServiceDelegate().getMaMessageTemplateService()
          .removeTemplate(wxAppMsgTemplate.getTemplateId());
      // 删除本地模板消息
      wxAppMsgTemplateService.delete(wxAppMsgTemplate);
      systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "微信消息模板删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 批量删除微信消息模板
   * 
   * @return
   */
  @RequestMapping(params = "doBatchDel")
  @ResponseBody
  public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "微信消息模板删除成功";
    try {
      for (String id : ids.split(",")) {
        WxAppMsgTemplateEntity wxAppMsgTemplate = systemService
            .getEntity(WxAppMsgTemplateEntity.class, id);
        wxAppMsgTemplateService.delete(wxAppMsgTemplate);
        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
      }
    } catch (Exception e) {
      e.printStackTrace();
      message = "微信消息模板删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 添加微信消息模板
   * 
   * @param ids
   * @return
   */
  @RequestMapping(params = "doAdd")
  @ResponseBody
  public AjaxJson doAdd(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "微信消息模板添加成功";

    try {

      if (StringUtil.isEmpty(wxAppMsgTemplate.getAppId())) {
        j.setMsg("请选择小程序");
        j.setSuccess(false);
        return j;
      } else if (StringUtil.isEmpty(wxAppMsgTemplate.getName())) {
        j.setMsg("请选择小程序模板标题");
        j.setSuccess(false);
        return j;
      } else if (StringUtil.isEmpty(wxAppMsgTemplate.getContent())) {
        j.setMsg("请至少选择一组关键词");
        j.setSuccess(false);
        return j;
      }
      String[] keywordList = wxAppMsgTemplate.getContent().split(",");
      List<Integer> keywordIdList = new ArrayList<Integer>();
      for (String keywordId : keywordList) {
        keywordIdList.add(Integer.parseInt(keywordId));
      }
      AddTemplateRequest req = new AddTemplateRequest();
      req.setId(wxAppMsgTemplate.getTemplateId());
      req.setKeywordIdList(keywordIdList);
      String templateId = wxComponentService.getMaServiceDelegate().getMaMessageTemplateService()
          .addTemplate(req);
      wxAppMsgTemplate.setTemplateId(templateId);
      j.setObj(wxAppMsgTemplate);

      wxAppMsgTemplateService.save(wxAppMsgTemplate);
      systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);

      int pageCount = 20;
      int offset = 0;

      // 更新模板消息内容
      Paging page = new Paging();
      page.setCount(pageCount);
      page.setOffset(offset);

      List<WxAppMsgTemplate> msgTemplateList = wxComponentService.getMaServiceDelegate()
          .getMaMessageTemplateService().queryTemplateList(page);
      for (WxAppMsgTemplate template : msgTemplateList) {
        if (template.getTemplateId().equals(wxAppMsgTemplate.getTemplateId())) {
          wxAppMsgTemplate.setContent(template.getContent());
          wxAppMsgTemplate.setExample(template.getExample());
          wxAppMsgTemplate.setName(template.getTitle());
          wxAppMsgTemplateService.saveOrUpdate(wxAppMsgTemplate);
          break;
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      message = "微信消息模板添加失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 更新微信消息模板
   * 
   * @param ids
   * @return
   */
  @RequestMapping(params = "doUpdate")
  @ResponseBody
  public AjaxJson doUpdate(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest request) {
    String message = null;
    AjaxJson j = new AjaxJson();
    message = "微信消息模板更新成功";
    WxAppMsgTemplateEntity t = wxAppMsgTemplateService.get(WxAppMsgTemplateEntity.class,
        wxAppMsgTemplate.getId());
    try {
      MyBeanUtils.copyBeanNotNull2Bean(wxAppMsgTemplate, t);
      wxAppMsgTemplateService.saveOrUpdate(t);
      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "微信消息模板更新失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 微信消息模板新增页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "goAdd")
  public ModelAndView goAdd(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(wxAppMsgTemplate.getId())) {
      wxAppMsgTemplate = wxAppMsgTemplateService.getEntity(WxAppMsgTemplateEntity.class,
          wxAppMsgTemplate.getId());
      req.setAttribute("wxAppMsgTemplatePage", wxAppMsgTemplate);
    }
    return new ModelAndView("com/gomore/wechat/component/message/wxAppMsgTemplate-add");
  }

  /**
   * 微信消息模板编辑页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "goUpdate")
  public ModelAndView goUpdate(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(wxAppMsgTemplate.getId())) {
      wxAppMsgTemplate = wxAppMsgTemplateService.getEntity(WxAppMsgTemplateEntity.class,
          wxAppMsgTemplate.getId());
      req.setAttribute("wxAppMsgTemplatePage", wxAppMsgTemplate);
    }
    return new ModelAndView("com/gomore/wechat/component/message/wxAppMsgTemplate-update");
  }

  /**
   * 导入功能跳转
   * 
   * @return
   */
  @RequestMapping(params = "upload")
  public ModelAndView upload(HttpServletRequest req) {
    req.setAttribute("controller_name", "wxAppMsgTemplateController");
    return new ModelAndView("common/upload/pub_excel_upload");
  }

  /**
   * 导出excel
   * 
   * @param request
   * @param response
   */
  @RequestMapping(params = "exportXls")
  public String exportXls(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
    CriteriaQuery cq = new CriteriaQuery(WxAppMsgTemplateEntity.class, dataGrid);
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, wxAppMsgTemplate,
        request.getParameterMap());
    List<WxAppMsgTemplateEntity> wxAppMsgTemplates = this.wxAppMsgTemplateService
        .getListByCriteriaQuery(cq, false);
    modelMap.put(NormalExcelConstants.FILE_NAME, "微信消息模板");
    modelMap.put(NormalExcelConstants.CLASS, WxAppMsgTemplateEntity.class);
    modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("微信消息模板列表",
        "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"));
    modelMap.put(NormalExcelConstants.DATA_LIST, wxAppMsgTemplates);
    return NormalExcelConstants.JEECG_EXCEL_VIEW;
  }

  /**
   * 导出excel 使模板
   * 
   * @param request
   * @param response
   */
  @RequestMapping(params = "exportXlsByT")
  public String exportXlsByT(WxAppMsgTemplateEntity wxAppMsgTemplate, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid, ModelMap modelMap) {
    modelMap.put(NormalExcelConstants.FILE_NAME, "微信消息模板");
    modelMap.put(NormalExcelConstants.CLASS, WxAppMsgTemplateEntity.class);
    modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("微信消息模板列表",
        "导出人:" + ResourceUtil.getSessionUserName().getRealName(), "导出信息"));
    modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
    return NormalExcelConstants.JEECG_EXCEL_VIEW;
  }

  @SuppressWarnings("unchecked")
  @RequestMapping(params = "importExcel", method = RequestMethod.POST)
  @ResponseBody
  public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
    AjaxJson j = new AjaxJson();

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
      MultipartFile file = entity.getValue();// 获取上传文件对象
      ImportParams params = new ImportParams();
      params.setTitleRows(2);
      params.setHeadRows(1);
      params.setNeedSave(true);
      try {
        List<WxAppMsgTemplateEntity> listWxAppMsgTemplateEntitys = ExcelImportUtil
            .importExcel(file.getInputStream(), WxAppMsgTemplateEntity.class, params);
        for (WxAppMsgTemplateEntity wxAppMsgTemplate : listWxAppMsgTemplateEntitys) {
          wxAppMsgTemplateService.save(wxAppMsgTemplate);
        }
        j.setMsg("文件导入成功！");
      } catch (Exception e) {
        j.setMsg("文件导入失败！");
        logger.error(ExceptionUtil.getExceptionMessage(e));
      } finally {
        try {
          file.getInputStream().close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return j;
  }

  @RequestMapping(method = RequestMethod.GET)
  @ResponseBody
  public List<WxAppMsgTemplateEntity> list() {
    List<WxAppMsgTemplateEntity> listWxAppMsgTemplates = wxAppMsgTemplateService
        .getList(WxAppMsgTemplateEntity.class);
    return listWxAppMsgTemplates;
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  @ResponseBody
  public ResponseEntity<?> get(@PathVariable("id") String id) {
    WxAppMsgTemplateEntity task = wxAppMsgTemplateService.get(WxAppMsgTemplateEntity.class, id);
    if (task == null) {
      return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity(task, HttpStatus.OK);
  }

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
  @ResponseBody
  public ResponseEntity<?> create(@RequestBody WxAppMsgTemplateEntity wxAppMsgTemplate,
      UriComponentsBuilder uriBuilder) {
    // 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
    Set<ConstraintViolation<WxAppMsgTemplateEntity>> failures = validator
        .validate(wxAppMsgTemplate);
    if (!failures.isEmpty()) {
      return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures),
          HttpStatus.BAD_REQUEST);
    }

    // 保存
    try {
      wxAppMsgTemplateService.save(wxAppMsgTemplate);
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity(HttpStatus.NO_CONTENT);
    }
    // 按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
    String id = wxAppMsgTemplate.getId();
    URI uri = uriBuilder.path("/rest/wxAppMsgTemplateController/" + id).build().toUri();
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uri);

    return new ResponseEntity(headers, HttpStatus.CREATED);
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.PUT,
      consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<?> update(@RequestBody WxAppMsgTemplateEntity wxAppMsgTemplate) {
    // 调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
    Set<ConstraintViolation<WxAppMsgTemplateEntity>> failures = validator
        .validate(wxAppMsgTemplate);
    if (!failures.isEmpty()) {
      return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures),
          HttpStatus.BAD_REQUEST);
    }

    // 保存
    try {
      wxAppMsgTemplateService.saveOrUpdate(wxAppMsgTemplate);
    } catch (Exception e) {
      e.printStackTrace();
      return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    // 按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
    return new ResponseEntity(HttpStatus.NO_CONTENT);
  }

  @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void delete(@PathVariable("id") String id) {
    wxAppMsgTemplateService.deleteEntityById(WxAppMsgTemplateEntity.class, id);
  }

  @RequestMapping(params = "selectTemplateTitle")
  public ModelAndView showTemplateTitles(HttpServletRequest request) {
    String appId = request.getParameter("appId");
    request.setAttribute("appId", appId);
    return new ModelAndView("com/gomore/wechat/component/message/msgTemplateTitleList");
  }

  @RequestMapping(params = "datagridTemplateTitle")
  public void datagridTemplateTitle(HttpServletRequest request, HttpServletResponse response,
      DataGrid dataGrid) throws WxErrorException, ServerException {
    String appId = request.getParameter("appId");
    if (StringUtil.isEmpty(appId)) {
      throw new ServerException("小程序appId不能为空");
    }
    WxAppContext.setAppId(appId);
    Paging page = new Paging();
    page.setCount(dataGrid.getRows() > 20 ? 20 : dataGrid.getRows());
    page.setOffset((dataGrid.getPage() - 1)*dataGrid.getRows());
    QueryTemplateTitleResponse resp = wxComponentService.getMaServiceDelegate()
        .getMaMessageTemplateService().queryTemplateTitleList(page);
    int allCounts = resp.getTotalCount();
    dataGrid.setResults(resp.getList());
    dataGrid.setTotal(allCounts);
    TagUtil.datagrid(response, dataGrid);
  }

  @RequestMapping(params = "selectTemplateTitleKeyword")
  public ModelAndView selectTemplateTitleKeyword(HttpServletRequest request) {
    String appId = request.getParameter("templateTitleId");
    request.setAttribute("templateTitleId", appId);
    return new ModelAndView("com/gomore/wechat/component/message/msgTemplateTitleKeyword");
  }

  @RequestMapping(params = "datagridTemplateKeyword")
  public void datagridTemplateKeyword(HttpServletRequest request, HttpServletResponse response,
      DataGrid dataGrid) throws WxErrorException, ServerException {
    String templateTitleId = request.getParameter("templateTitleId");
    if (StringUtil.isEmpty(templateTitleId)) {
      throw new ServerException("templateTitleId不能为空");
    }
    List<WxAppMsgTemplateLibKeyword> keywords = wxComponentService.getMaServiceDelegate()
        .getMaMessageTemplateService().getTemplateTitleKeywordById(templateTitleId);
    int allCounts = keywords.size();
    int pageSize = dataGrid.getRows();// 每页显示数

    // 分页展示
    List<WxAppMsgTemplateLibKeyword> currentKeywords = new ArrayList<WxAppMsgTemplateLibKeyword>();
    if (pageSize * dataGrid.getPage() < allCounts) {
      currentKeywords.addAll(
          keywords.subList(pageSize * (dataGrid.getPage() - 1), pageSize * dataGrid.getPage()));
    } else {
      currentKeywords.addAll(keywords.subList(pageSize * (dataGrid.getPage() - 1), allCounts));
    }
    dataGrid.setResults(currentKeywords);
    dataGrid.setTotal(allCounts);
    TagUtil.datagrid(response, dataGrid);
  }
}
